package org.zfes.snowy.ss.config.dynamicds;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.zfes.snowy.base.datasource.DynamicDataSourceContextHolder;
import org.zfes.snowy.base.datasource.TargetDataSource;
import org.zfes.snowy.core.exceptions.AppRuntimeException;
//https://yq.aliyun.com/articles/8302
@Aspect
//@Scope
@Order(-99)// 
@Component
public class DynamicDataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

   // @Before("@annotation(org.zfes.snowy.base.datasource.TargetDataSource)")
    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
    	String dsId = ds.name();
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            logger.error("datasource[{}]is not exsits > {}", dsId, point.getSignature());
            throw new AppRuntimeException("数据源不存在");
        } else {
            logger.debug("Use DataSource : {} > {}", dsId, point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceType(dsId);
        }
    }

//    @Before("@annotation(org.zfes.snowy.base.datasource.TargetDataSource) && args(ds)")
//    public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
//        String dsId = ds.name();
//        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
//            logger.error("datasource[{}]is not exsits > {}", ds.name(), point.getSignature());
//            throw new AppRuntimeException("数据源不存在");
//        } else {
//            logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
//            DynamicDataSourceContextHolder.setDataSourceType(ds.name());
//        }
//    }

//    @After("@annotation(org.zfes.snowy.base.datasource.TargetDataSource)&& args(ds)")
    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
        logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
